#!/usr/bin/env python
'''
Created on Jan 29, 2012

@author: shashank
'''
from pymongo import Connection

class InvalidDatabaseName(Exception):
    
    def __init__(self, db):
        self.db = db
    
    def __str__(self):
        return self.db

class CoreDB:
    """
    Class which manages Mongo DB core routines
    """
    
    def __init__(self, name, server = 'localhost', port = 27017):
        self.server = server
        self.port = port
        self.name = name
        self.db = None
        if server and port and name:
            self.db = self.__get_db__()
            print "Connected to mongodb://%s:%s/%s"%(self.server, self.port, self.name)
        
    def __get_db__(self):
        """
        Connect to the database and return a database object
        Unlike mongo db 
        """
        c = Connection(host=self.server, port=self.port)
        if self.name in c.database_names():
            return getattr(c, self.name)
        raise InvalidDatabaseName(self.name)
    
    def add(self, row, allow_duplicate=False):
        """
        Insert a document(record/row) in a collection(table).
        c -> database connection
        row -> dictionary(document) to be inserted in to the database.
        """
        if not allow_duplicate and self.query(row).next():
            print "Row already exists in db, skipping"
            return None
        return self.db.collection.insert(row)

    def query(self, filter):
        """
        Get the document from the database.
        c -> database connection
        filter -> dict with key value pair which is to be used for document
                  search.
        """
        return self.db.collection.find(filter)
    
    def delete(self, filter):
        """
        Delete the document that matched the filter criteria
        c -> database connection
        filter -> dict which identifies the document to delete.
        """
        return self.db.collection.remove(filter)

    def close(self):
        """
        Close the database connection
        """
        print "Closing connection to mongodb://%s:%s/%s"%(self.server, self.port, self.name)
        return self.db.logout()
    
    def __enter__(self):
        """
        Implementing WITH protocol
        """
        return self
    
    def __exit__(self, exc_type, exc_value, traceback):
        """
        Implementing WITH protocol
        """
        self.close()
        if traceback:
            return False
        return True